-module(gtp_session_server).
-behavior(gen_server).
-include("protocol.hrl").
-include("cdr.hrl").
-export([start/0,start_link/0,start_link/0,init/1,handle_call/3,handle_cast/2,handle_info/2,terminate/2,code_change/3]).
-export([handle/2]).
-record(gtp_state,{
	state = initialized,
	teid_1 = 0,
	teid_2 = 0,
	timer
}).
-define(session_timeout,1000).
handle(Pid,Request) ->
	gen_server:cast(Pid,Request).
start()  ->
	gen_server:start(?MODULE, [], []). 
start_link() ->
	gen_server:start_link(?MODULE, [], []).
init([]) ->
	error_logger:info_msg("gtp session server start..."),
	{ok,Timer} = timer:apply_after(?session_timeout,?MODULE,handle,[self(),timeout]),
	{ok,{running,{#gtp_state{timer = Timer},#lte_gtp_cdr{}}}}.
handle_call(_,_,_State) ->
	{reply, {error,"no func define gtp server"}, {}}.
handle_cast({packet_comming,P_Tuple},{running,{State,CDR}}) ->
	timer:cancel(State#gtp_state.timer),
	{ok,Timer} = timer:apply_after(?session_timeout,?MODULE,handle,[self(),timeout]),
	NewState = State#gtp_state{timer=Timer},
	case P_Tuple#packet_tuple.packet of
	<<2:3,0:1,1:1,0:3, ?CREATE_SESSION_REQUEST,_Length:16,0:32,SeqNo:24,_/binary>> ->
		{noreply,{running,{NewState#gtp_state{state=creating},?cdr_set_start_time(lte_gtp_cdr,CDR,P_Tuple#packet_tuple.datetime)}}};
	<<2:3,0:1,1:1,0:3, ?CREATE_SESSION_RESPONSE,_Length:16,0:32,SeqNo:24,_/binary>> ->
		{noreply,{running,{NewState#gtp_state{state=created},CDR}}};
	_ ->
		{noreply,{running,{NewState,CDR}}}
	end;
handle_cast(timeout, State) ->
	io:format("session server timeout~n"),
	{stop,timeout,State};
handle_cast(_, State) ->
	{noreply,State}.
handle_info(_, State) ->
	{noreply,State}.
terminate(_, _) ->
	ok.
code_change(_, State, _) ->
	{ok,State}.	
